import axios from "axios";
import Cookies from "js-cookie";

export default function(url, data = {}, type = "GET") {
  return new Promise(function(resolve, reject) {
    let promise;
    const instance = axios.create({
      headers: {
        csrf: Cookies.get("kw_token")
      }
    });
    if (type.toUpperCase() == "GET") {
      let dataStr = "";
      if (data) {
        Object.keys(data).forEach(key => {
          dataStr += key + "=" + data[key] + "&";
        });
      }
      if (dataStr !== "") {
        dataStr = dataStr.substring(0, dataStr.lastIndexOf("&"));
        url = url + "?" + dataStr;
      }
      promise = instance.get(url);
    } else {
      promise = instance.post(url, data);
    }
    promise
      .then(response => {
        resolve(response.data);
      })
      .catch(err => {
        reject(err);
      });
  });
}
